<template>
  <div class="shape" :class="{ active }" @mousedown="handleMouseDownOnShape">
    <slot></slot>
  </div>
</template>

<script>
export default {
  props: {
    active: {
      type: Boolean,
      default: false,
    },
    element: {
      require: true,
      type: Object,
      default: () => {},
    },
    index: {
      require: true,
      type: [Number, String],
      default: 0,
    },
    defaultStyle: {
      require: true,
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {};
  },

  mounted() {},

  methods: {
    handleMouseDownOnShape(e) {
      this.$store.commit("setClickComponentStatus", true);
      if (
        this.element.component != "v-text" &&
        this.element.component != "rect-shape"
      ) {
        e.preventDefault();
      }

      e.stopPropagation();
      this.$store.commit("setCurComponent", {
        component: this.element,
        index: this.index,
      });
      if (this.element.isLock) return;

      const pos = { ...this.defaultStyle };
      const startY = e.clientY;
      const startX = e.clientX;
      // 如果直接修改属性，值的类型会变为字符串，所以要转为数值型
      const startTop = Number(pos.top);
      const startLeft = Number(pos.left);

      const move = (moveEvent) => {
        // hasMove = true;
        const curX = moveEvent.clientX;
        const curY = moveEvent.clientY;
        pos.top = curY - startY + startTop;
        pos.left = curX - startX + startLeft;

        // 修改当前组件样式
        this.$store.commit("setShapeStyle", pos);
      };

      const up = () => {
        document.removeEventListener("mousemove", move);
        document.removeEventListener("mouseup", up);
      };

      document.addEventListener("mousemove", move);
      document.addEventListener("mouseup", up);
    },
  },
};
</script>
<style lang="less">
.shape {
  position: absolute;

  &:hover {
    cursor: move;
  }
}
.active {
  outline: 1px solid #70c0ff;
  user-select: none;
}
</style>
